package halberd.filter;

import halberd.DataType;
import halberd.data.ImgData;
import halberd.data.ImgDataFactory;

/**
 * 直方图均衡化
 * 
 * @author jiang
 *
 */
public class HistogramEqualizationFilter {
	public ImgData process(ImgData input) {
		if (!canProcess(input)) {
			return null;
		}
		ImgData result = ImgDataFactory.createImgData(input.getWidth(), input.getHeight());
		int[][][] ints = input.getDatas();
		histogramEqualization(ints, result.getDatas(), input.getWidth(), input.getHeight());
		result.setDataType(DataType.GRAY);
		return result;
	}

	private boolean canProcess(ImgData input) {
		if(input==null) {
			return false;
		}
		DataType dt=input.getDataType();
		if(dt==DataType.GRAY) {
			return true;
		}
		return false;
	}

	private void histogramEqualization(int[][][] src, int[][][] dst, int Width, int Height) {
		int[] temp_count = new int[256];// 累加
		double[] midu = new double[256];// 0-1之间密度
		double[] midu_count = new double[256];// 0-1之间密度累加
		int[] junheng = new int[256];
		int W = Width;
		int H = Height;
		for (int i = 0; i < 256; ++i) {
			temp_count[i] = 0;
			midu[i] = 0;
			midu_count[i] = 0;
		}
		for (int i = 0; i < W; i++) {
			for (int j = 0; j < H; j++) {
				temp_count[src[i][j][4]] += 1;
			}
		}
		for (int i = 0; i < 256; ++i) {
			midu[i] = temp_count[i] * 1.0 / W / H;
		}
		midu_count[0] = midu[0];
		for (int i = 1; i < 256; ++i) {
			midu_count[i] = midu_count[i - 1] + midu[i];
		}
		for (int i = 1; i < 256; ++i) {
			junheng[i] = (int) (255.0f * midu_count[i] + 0.5f);
		}
		for (int i = 0; i < W; i++) {
			for (int j = 0; j < H; j++) {
				dst[i][j][4] =  junheng[src[i][j][4]];
			}
		}
		return;
	}
}
